package com.nisum.mocksimulator.consumer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.nisum.mocksimulator.externalize.ExternalizableMessageReader;
import com.nisum.mocksimulator.externalize.ExternalizableMessageWriter;
import com.nisum.mocksimulator.notifier.DirectoryListener;
import com.nisum.mocksimulator.notifier.DirectoryNotifier;
import com.nisum.mocksimulator.webservice.beans.Car4x4Type;
import com.nisum.mocksimulator.webservice.beans.CarType;

@Component
public class CarConsumerService {
	private final int SLEEP_SERVICE_TIME = 1000;
	@Autowired
	@Qualifier("4x2")
	private CarType car;
	@Autowired
	@Qualifier("4x4")
	private Car4x4Type _4x4Car;
	// Could not use auto-wiring. Library restricts it
	private DirectoryNotifier notifier;
	@Autowired
	private DirectoryListener listener;
	@Autowired
	private ExternalizableMessageWriter writer;
	@Autowired
	private ExternalizableMessageReader reader;
	
	@Value("c:\\temp\\")
	private String DIRECTORY_TO_READ;
	@Value("c:\\temp_2\\")
	private String DIRECTORY_TO_WRITE;

	public void initService() {
		notifier = new DirectoryNotifier();
		reader.setDirectory(DIRECTORY_TO_READ);
		writer.setDirectory(DIRECTORY_TO_WRITE);
		notifier.configureDirectoryNotifier(DIRECTORY_TO_READ, true);
		notifier.start(listener);
		listenDirectory();
	}

	private void listenDirectory() {
		System.out.println("Sleep service time is "+SLEEP_SERVICE_TIME);
		do {
			try {
				Thread.sleep(SLEEP_SERVICE_TIME);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			if (listener.isFileModified()) {
				System.out.println("JNotify detected a modification on dir: "
						+ DIRECTORY_TO_READ);
				this.car = (CarType) reader.read(listener.getFileName());
				System.out
						.println("CarConsumerService inflated CarType object: "
								+ this.car.toString());
				construct4x4Car(this.car);
				writer.write(this._4x4Car);
				System.out
						.println("CarConsumerService created Car4x4Type object: "
								+ this._4x4Car.toString());
				listener.setFileModified(false);
			}
		} while (true);
	}

	private void construct4x4Car(CarType car) {
		this._4x4Car.setName(car.getName());
		this._4x4Car.setYear(car.getYear());
		this._4x4Car
				.setAltClimb(Car4x4Type.HillAltitudeClimb.values()[(int) (Math
						.random() * 3 + 1)]);
		this._4x4Car
				.setAngleClimb(Car4x4Type.HillAngleClimb.values()[(int) (Math
						.random() * 3 + 1)]);
	}
}
